const Koa = require('koa');
const serve = require('koa-static-server')
const path = require('path')
const fs = require('fs')
const os = require('os')
const app = new Koa();

app.use(serve({rootDir: 'css', rootPath: '/css'}))
app.use(serve({rootDir: 'lib', rootPath: '/lib'}))
app.use(serve({rootDir: 'js', rootPath: '/js'}))
app.use(serve({rootDir: 'page', rootPath: '/page'}))
app.use(serve({rootDir: 'api', rootPath: '/api'}))

const apiDir = path.join(__dirname, 'api')
const dirFileList = []
const getDirFileList = function (dirName) {
    const fileList = fs.readdirSync(dirName)
    if (Array.isArray(fileList) && fileList.length) {
        fileList.forEach(file => {
            const filePath = path.join(dirName, file)
            const fileStat = fs.statSync(filePath)
            if (fileStat) {
                if (fileStat.isDirectory()) {
                    getDirFileList(filePath)
                } else if (fileStat.isFile()) {
                    dirFileList.push({
                        router: filePath.replace(apiDir, '').replace(/\\/g, '/'),
                        path: filePath
                    })
                }
            }
        })
    }
}
getDirFileList(apiDir)
const apiRouters = {}
dirFileList.forEach(dirItem => {
    apiRouters[dirItem.router] = dirItem
})

// fs.readdir(apiDir, function (err, files) {
//     for (var i = 0; i < files.length; i++) {
//         fs.stat(path.join(apiDir, files[i]), function (err, data) {
//             if (data.isFile()) {
//                 dirFileList.push(files[i]);
//             }
//         });
//     }
//     console.log(dirFileList);
// });
app.use(async ctx => {
    const url = ctx.url
    if (url === '/' || url === '/index.html') {
        const indexHtmlPath = path.join(__dirname, 'index.html')
        const data = fs.readFileSync(indexHtmlPath, 'utf-8');
        if (data) {
            ctx.body = data
        } else {
            ctx.body = 'hello world';
        }

    } else {
        const router = url.endsWith('.json') ? url : url + '.json'
        if (apiRouters[router]) {
            const data = fs.readFileSync(apiRouters[router].path, 'utf-8');
            if (data) {
                ctx.body = data
            } else {
                ctx.body = 'hello world';
            }
        } else {
            ctx.body = 'hello world';
        }
    }
});

app.listen(3000)

function getIPAdress() {
    var interfaces = os.networkInterfaces();
    for (var devName in interfaces) {
        var iface = interfaces[devName];
        for (var i = 0; i < iface.length; i++) {
            var alias = iface[i];
            if (alias.family === 'IPv4' && alias.address !== '127.0.0.1' && !alias.internal) {
                return alias.address;
            }
        }
    }
}
const localIp = getIPAdress()
console.log('http://localhost:3000')
if (localIp) {
    console.log('http://' + localIp + ':3000')
}
